//
//  WBUserAccount.swift
//  weiboswift
//
//  Created by dingzhibing on 2017/3/28.
//  Copyright © 2017年 dingzhibing. All rights reserved.
//

import UIKit
private let accountFile:NSString = "useraccount.json"
class WBUserAccount: NSObject {
    //访问令牌
    var access_token:String?
    //用户代号
    var uid:String?
    
    //过期日期，单位秒
    //开发者5年，使用者3天
    var expires_in:TimeInterval = 0 {
        didSet{
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    
    var expiresDate:Date?  //过期日期
    
    //昵称
    var screen_name: String?
    //用户头像
    var avatar_large: String?
    
    override var description: String{
        return yy_modelDescription()
    }
    
    override init(){
        super.init()
        
        //从磁盘加载保存的文件
        guard let path = accountFile.cz_appendDocumentDir(),
            let data = NSData(contentsOfFile: path),
        let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String:AnyObject] else{
                return
        }
        
        //使用字典设置属性
        yy_modelSet(with: dict ?? [:])
        
        print("加载沙盒信息 \(self)")
        
        //判断token是否过期
        //expiresDate = Date(timeIntervalSinceNow: -3600 * 24)
        if expiresDate?.compare(Date()) != .orderedDescending {
            print("token过期")
            
            //情空token
            access_token = nil
            uid = nil
            
            //删除文件
            //FileManager.default.removeItem(at: path)
            _ = try? FileManager.default.removeItem(atPath: path)
        }
        print("token未过期")
    }
    
    /**
     偏好设置（存储小数据 xcode8 beta无效）
     沙盒-归档／plist／json
     数据库（FMDB／CoreData）
     钥匙串访问(存储小数据／自动加密 - 不能用oc直接写，需要使用 SSKeychain框架)
     */
    func saveAccount(){
        //1. 模型转字典
        var dict = (self.yy_modelToJSONObject() as? [String:AnyObject]) ?? [:]
        
        //删除expires_in 不需要保存
        dict.removeValue(forKey: "expires_in")
        //2. 字典序列化  data
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []),
            let filePath = accountFile.cz_appendDocumentDir()
            else{
                return
            }
        //3. 写入磁盘
        (data as NSData).write(toFile: filePath, atomically: true)
        
        print("用户账户保存成功\(filePath)")
        
    }
}
